"use strict"

module.exports = function(db, options){
  var express = require("express");
  var _ = require("lodash");
  var debug = require('debug')('qywx-api');
  var thisapp = express();

  require("./models")(db); //Merge localDB with global DB

  thisapp.on('mount', function (parent) {
    debug('===> qywx api app Mounted');
    //Initialize the x_account_config of parent app
    if(_.isEmpty(thisapp.locals.accountConfigs)){
      db.sequelize.model("AccountConfig")
        .findAll()
        .then(function(instances){
          if(!instances){
            return next();
          }
          var accountConfigs = { };
          instances.map(function(currentObject, index, thisArray){
             var configObj = {}

             configObj[currentObject.corpId] = JSON.parse(JSON.stringify(currentObject))
              _.assign(accountConfigs, configObj)
          })

          thisapp.locals.accountConfigs = accountConfigs;
          parent.locals.accountConfigs = accountConfigs;

          debug("Projected APP local accountConfigs ==>", parent.locals.accountConfigs)
          /**
           * The generated accountConfig:
           * { wx42c1a7f89c4a258d:
               { id: 1,
                 corpId: 'wx42c1a7f89c4a258d',
                 groupName: 'TESTTEST',
                 secret: 'BrMySu4oO_J2psgOkMKaZ0K6NexnI0pNeOPC9F-L5nARiJqSLYY_7I9NVWL0YGca',
                 jwtAccessTokenSecret: 'mLhYKdAONOvmwh85srV3t5IRrEaI4VRFqgzErptEK7IVIYLnXu8KYmhXV1deZRWa',
                 jwtAccessTokenExpiresIn: 604800000,
                 jwtAccessTokenAlgorithm: 'HS512',
                 singleRowLock: 0,
                 created_at: '2016-07-01T03:16:22.849Z',
                 updated_at: '2016-07-01T03:16:22.849Z',
                 deleted_at: null }
              }
           */
        })
    }
  });

  // thisapp.use(function(req, res, next){
  //   //Initialize module if account config not setup
  //   debug("accountConfigs exist? ==> ", thisapp.locals.accountConfigs)
  //   if(_.isEmpty(thisapp.locals.accountConfigs)){
  //     db.sequelize.model("AccountConfig")
  //       .findAll()
  //       .then(function(instances){
  //         if(!instances){
  //           return next();
  //         }
  //         var accountConfigs = { };
  //         instances.map(function(currentObject, index, thisArray){
  //            var configObj = {}
  //
  //            configObj[currentObject.corpId] = JSON.parse(JSON.stringify(currentObject))
  //             _.assign(accountConfigs, configObj)
  //         })
  //
  //         thisapp.locals.accountConfigs = accountConfigs;
  //
  //         debug("Projected APP local accountConfigs ==>", thisapp.locals.accountConfigs)
  //         return next();
  //       })
  //   }else{
  //     return next();
  //   }
  // })

  //TODO: Add a system API to force refresh qywxAccountConfig

  //include controllers
  require("./controllers/AuthController")(thisapp, db, options);

  return thisapp
}
